var CryptoJS = require('./aes.js');

CryptoJS.pad.NoPadding = {
  pad: function () {
  },

  unpad: function () {
  }
};

CryptoJS.mode.ECB = (function () {
  var ECB = CryptoJS.lib.BlockCipherMode.extend();

  ECB.Encryptor = ECB.extend({
    processBlock: function (words, offset) {
      this._cipher.encryptBlock(words, offset);
    }
  });

  ECB.Decryptor = ECB.extend({
    processBlock: function (words, offset) {
      this._cipher.decryptBlock(words, offset);
    }
  });

  return ECB;
}());

function getKeyBuffer(val) {
  // if (val_Key) {
  var val_Key = '9351462D67C7BD10919F0CF8E659D4A272540485F52CEA4CEEBBF6B748A06D8D';
  var typedArray = new Uint8Array(val_Key.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16);
  }))
  var buffer1 = typedArray.buffer;
  var arrayInt8Array = new Int8Array(buffer1);
  return arrayInt8Array;
  // }
}

// 加解密用到的密钥
function aesKeyBytes() {
  var key_Int = new Int8Array(getKeyBuffer());
  var keyBytes = int8parse(key_Int);
  return keyBytes;
}

// 十六进制字符串数组，个数如果不足16整数倍则补0
function hexTo16Hex(str) {
  var diff = 16 - (str.length + 1) / 3 % 16;
  for (var i = 0; i < diff; i++) {
    str = str + " 00";
  }
  return str;
}

// AES加密
function encrypt(str) {
  var decArray = hexStrToDecArray(str);
  var wordArray = int8parse(decArray);
  var encrypted = CryptoJS.AES.encrypt(wordArray, aesKeyBytes(), {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.NoPadding
  });
  return wordArrayToHexStr(encrypted.ciphertext.words);
}

// AES解密
function decrypt(str) {
  var decArray = hexStrToDecArray(str);
  var wordArray = int8parse(decArray);
  var base64Str = CryptoJS.enc.Base64.stringify(wordArray);
  var decrypted = CryptoJS.AES.decrypt(base64Str, aesKeyBytes(), {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.NoPadding
  });
  return wordArrayToHexStr(decrypted.words);
}

// 构建WordArray对象
function int8parse(u8arr) {
  var len = u8arr.length;
  var words = [];
  for (var i = 0; i < len; i++) {
    words[i >>> 2] |= (u8arr[i] & 0xff) << (24 - (i % 4) * 8);
  }
  return CryptoJS.lib.WordArray.create(words, len);
}

// 十六进制字符串(空格分割)转成十进制数字的数组
function hexStrToDecArray(str) {
  var strArray = str.split(" ");
  var decArray = [];
  for (var i = 0; i < strArray.length; i++) {
    decArray.push(parseInt(strArray[i], 16));
  }
  return arrayTo16Array(decArray);
}

// 十进制数组转成十六进制字符串
function decArrayToHexStr(array) {
  var hexStr = "";
  for (var i = 0; i < array.length; i++) {
    var str = array[i].toString(16).toUpperCase();
    if (str.length < 2) {
      str = "0" + str;
    }
    hexStr = hexStr + str + " ";
  }
  return hexStr.substr(0, hexStr.length - 1);
}

// word类型的十进制数组转成十六进制字符串
function wordArrayToHexStr(array) {
  var hexStr = "";
  for (var i = 0; i < array.length; i++) {
    var num = array[i];
    if (num < 0) {
      num = array[i] + 0x100000000;
    }
    var str = num.toString(16).toUpperCase();
    var fullStr = str;
    if (str.length < 8) {
      for (var j = 0; j < 8 - str.length; j++) {
        fullStr = "0" + fullStr;
      }
    }
    hexStr = hexStr + fullStr;
  }
  var ret = "";
  for (var i = 0; i < hexStr.length; i += 2) {
    ret = ret + hexStr.substr(i, 2) + " "
  }
  return ret.substr(0, ret.length - 1);
}

// 数组元素个数必须是16的整数倍，不足的在后面补0
function arrayTo16Array(array) {
  var len = array.length;
  var distLen = parseInt((array.length - 1) / 16) * 16 + 16;
  for (var i = array.length; i < distLen; i++) {
    array[i] = 0;
  }
  return array;
}

function Utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;
  out = "";
  len = array.length;
  i = 0;
  while (i < len) {
    c = array[i++];
    switch (c >> 4) {
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx 10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx 10xx xxxx 10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
          ((char2 & 0x3F) << 6) |
          ((char3 & 0x3F) << 0));
        break;
    }
  }
  return out;
}

// 将一位数组或者字符串或者对象分割成每n个一组
function transTwoArry(str) {
  var result = "";
  for (var i = 0, len = str.length; i < len; i++) {
    result += str[i];
    if (i>2) {
      if (i % 2 == 1) result += ' ';
    }
  }
  return result;
}

//暴露接口
module.exports = {
  encrypt: encrypt,
  decrypt: decrypt,
  transTwoArry: transTwoArry,
  getKeyBuffer: getKeyBuffer,
  CryptoJS2: CryptoJS
}